package com.sita.bike.ui.view;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.Interpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Scroller;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapOptions;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.TextureMapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyTrafficStyle;
import com.sita.bike.R;
import com.sita.bike.event.CurtainIsShownEvent;
import com.sita.bike.event.SpeedActionEvent;
import com.sita.bike.support.Constants;
import com.sita.bike.support.GlobalContext;
import com.sita.bike.ui.activity.DataAnalysisActivity;
import com.sita.bike.utils.BitmapUtils;
import com.sita.bike.utils.FormatUtils;
import com.sita.bike.utils.LogUtils;
import com.sita.friend.FriendHelper;
import com.sita.tboard.ui.activity.RankingActivity;
import com.sita.tboard.ui.view.SpeedMeterView;
import com.sita.tboard.ui.view.SpeedMeterView.SPEED_STATUS;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;
import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.Line;
import lecho.lib.hellocharts.model.LineChartData;
import lecho.lib.hellocharts.model.PointValue;
import lecho.lib.hellocharts.model.ValueShape;
import lecho.lib.hellocharts.model.Viewport;
import lecho.lib.hellocharts.view.LineChartView;

public class NewCurtainView extends RelativeLayout implements OnTouchListener {

    private static String TAG = NewCurtainView.class.getSimpleName();
    public boolean isOpen = true;
    public RelativeLayout mSpeedMeterAllLayout;
    private Context mContext;
    private Scroller mScroller;
    private int upY = 0;
    private int downY = 0;
    private int moveY = 0;
    private int scrollY = 0;
    private int curtainHeigh = 0;
    private boolean isMove = false;
    private SpeedMeterView mSpeedMeter;
    private RelativeLayout mCurtainRope;
    private CircularProgressBar mStatTotalDistance;
    private CircularProgressBar mStatTotalTime;
    private CircularProgressBar mStatTop;
    private CircularProgressBar mStatAverSpeed;

    private TextView mTvRecent;
    private TextView mTvSpeed;
    private LinearLayout mLayoutStat;
    private RelativeLayout mLayoutSpeedChart;
    private LineChartView mSpeedChart;
    private LineChartData mSpeedChartData;


    private Line SpeedLine;
    private Line GLine;
    private static final int SPEED_COLOR = GlobalContext.getGlobalContext().getResources().getColor(R.color.speed_chart_speed_edge_color);
    private static final int G_COLOR = GlobalContext.getGlobalContext().getResources().getColor(R.color.speed_chart_g_edge_color);
    private int mPointIndex = 0;
    private int mMaxSpeedIndex = 0;
    private int mMaxSpeedInWindow = 0;
    private final int MAX_SPEED = 200;
    private int mSpeedChartWindowSize = 60 * 1; // one point every 1sec

    ArrayList<PointValue> mSpeedPointValueList = new ArrayList<>();
    ArrayList<PointValue> mGPointValueList = new ArrayList<>();

    private int upDuration = 700;
    private int downDuration = 500;
    private int speedMeterViewHeight;
    private SpeedMeterView.SPEED_STATUS mSpeedViewStatus;


    private static final CameraPosition DEFAULT_CAMERA_POSITION = new CameraPosition.Builder()
            .target(Constants.DEFAULT_LATLNG).zoom(Constants.DEFAULT_ZOOM_LEVEL).bearing(0).tilt(0).build();
    protected AMap aMap;
    private TextureMapView mSmallMapView;
    protected Marker myMarker;
    private ImageView mPowerOff;
    private ImageView mDashBoard;


    public NewCurtainView(Context context) {
        super(context);
        init(context);
    }

    public NewCurtainView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context);
    }

    public NewCurtainView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    private void init(final Context context) {
        this.mContext = context;
        Interpolator interpolator = new DecelerateInterpolator();
        mScroller = new Scroller(context, interpolator);

        this.setBackgroundColor(Color.argb(0, 0, 0, 0));
        final View view = LayoutInflater.from(mContext).inflate(R.layout.curtain_new, null);

        mPowerOff = (ImageView) view.findViewById(R.id.img_power_off);
        // no need to add click event here;

        mSpeedMeter = (SpeedMeterView) view.findViewById(R.id.circleprobar);
        mSpeedMeter.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG, "onClick: start");
                SPEED_STATUS newStatus = mSpeedMeter.getSpeedStatus();
                if (mSpeedViewStatus == newStatus) {
                    return;
                }
                // notify the parent UI
                if (mSpeedViewStatus == SPEED_STATUS.SPEED_STATUS_READY &&
                        newStatus == SPEED_STATUS.SPEED_STATUS_RUNNING) {
                    // reset speed chart
                    resetViewport();
                    resetChartData();

                    EventBus.getDefault().post(new SpeedActionEvent(SpeedActionEvent.ACTION_START));
                }
                if (mSpeedViewStatus == SPEED_STATUS.SPEED_STATUS_RUNNING &&
                        newStatus == SPEED_STATUS.SPEED_STATUS_OVER ||
                        newStatus == SPEED_STATUS.SPEED_STATUS_READY) {
//                    EventBus.getDefault().post(new SpeedActionEvent(SpeedActionEvent.ACTION_OVER));
                }
                if (mSpeedViewStatus == SPEED_STATUS.SPEED_STATUS_RUNNING &&
                        newStatus == SPEED_STATUS.SPEED_STATUS_PAUSED) {
//                    EventBus.getDefault().post(new SpeedActionEvent(SpeedActionEvent.ACTION_PAUSED));
                }

                if (mSpeedViewStatus == SPEED_STATUS.SPEED_STATUS_RUNNING &&
                        newStatus == SPEED_STATUS.SPEED_STATUS_MAP) {
                    onRopeClick();
                    return; // no need to switch status;
                }

                // update own UI
                mSpeedViewStatus = newStatus;
                switchStatus();

            }
        });
        mSpeedViewStatus = mSpeedMeter.getSpeedStatus();

        mStatTotalTime = (CircularProgressBar) view.findViewById(R.id.speed_stat_total_time);
        mStatTotalTime.setProgress(50);

        mStatTotalDistance = (CircularProgressBar) view.findViewById(R.id.speed_stat_total_distance);
        mStatTotalDistance.setProgress(40);


        mStatTotalDistance.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mContext.startActivity(new Intent(mContext, DataAnalysisActivity.class));
            }
        });

        mStatAverSpeed = (CircularProgressBar) view.findViewById(R.id.speed_stat_aver_speed);
        mStatAverSpeed.setProgress(80);


        mStatTop = (CircularProgressBar) view.findViewById(R.id.speed_stat_top);
        mStatTop.setProgress(90);
        mStatTop.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mContext.startActivity(new Intent(mContext, RankingActivity.class));
            }
        });

        mSpeedChart = (LineChartView) view.findViewById(R.id.speed_chart);
        // Init Speed Chart
        initLines();
        // Disable viewpirt recalculations, see toggleCubic() method for more info.
        mSpeedChart.setViewportCalculationEnabled(false);
        resetViewport();

        mTvRecent = (TextView) view.findViewById(R.id.speed_recent);
        mTvSpeed = (TextView) view.findViewById(R.id.speed_speed);
        mLayoutStat = (LinearLayout) view.findViewById(R.id.speed_recent_stat_layout);
        mLayoutSpeedChart = (RelativeLayout) view.findViewById(R.id.speed_chart_layout);
        mCurtainRope = (RelativeLayout) view.findViewById(R.id.layout_img_curtain_rope);
        mSpeedMeterAllLayout = (RelativeLayout) view.findViewById(R.id.speed_info_layout);
        addView(view);
        //为整个布局监听touch事件
        mSpeedMeterAllLayout.setOnTouchListener(this);
        mSpeedMeter.post(new Runnable() {

            @Override
            public void run() {
                curtainHeigh = mSpeedMeterAllLayout.getHeight();
            }
        });

        mSmallMapView = (TextureMapView) view.findViewById(R.id.small_mapview);
        mSmallMapView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isOpen) {
                    NewCurtainView.this.startMoveAnim(0, curtainHeigh, upDuration);
                    mSpeedMeter.showSpeedMeter(false);
                }
            }
        });

        switchStatus();
    }

    private void switchStatus() {
        switch (mSpeedViewStatus) {
            case SPEED_STATUS_READY: {
                mTvRecent.setVisibility(VISIBLE);
                mLayoutStat.setVisibility(VISIBLE);

                mPowerOff.setVisibility(INVISIBLE);
                mTvSpeed.setVisibility(INVISIBLE);
                mLayoutSpeedChart.setVisibility(INVISIBLE);
                mSmallMapView.setVisibility(INVISIBLE);
                break;
            }
            case SPEED_STATUS_RUNNING: {
                mTvRecent.setVisibility(INVISIBLE);
                mLayoutStat.setVisibility(INVISIBLE);

                mPowerOff.setVisibility(VISIBLE);
                mTvSpeed.setVisibility(VISIBLE);
                mLayoutSpeedChart.setVisibility(VISIBLE);
                mSmallMapView.setVisibility(VISIBLE);
                break;
            }
            case SPEED_STATUS_PAUSED:
            case SPEED_STATUS_OVER:
                break;
        }

    }

    /********************************
     *
     ********************************/
    public void startMoveAnim(int startY, int dy, int duration) {
        isMove = true;
        mScroller.startScroll(0, startY, 0, dy, duration);
        invalidate();
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
    }

    @Override
    public void computeScroll() {
        if (mScroller.computeScrollOffset()) {
            scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
            postInvalidate();
            isMove = true;
            mSpeedMeter.setMove(true);
        } else {
            isMove = false;
            mSpeedMeter.setMove(false);
        }
        super.computeScroll();
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        // TODO Auto-generated method stub
        if (!isMove) {
            int offViewY = 0;
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    downY = (int) event.getRawY();
                    offViewY = downY - (int) event.getX();
                    return true;
                case MotionEvent.ACTION_MOVE:
                    moveY = (int) event.getRawY();
                    scrollY = moveY - downY;
                    if (scrollY < 0) {
                        if (isOpen) {
                            if (Math.abs(scrollY) <= mSpeedMeter.getBottom() - offViewY) {
                                scrollTo(0, -scrollY);
                            }
                        }
                    } else {
                        if (!isOpen) {
                            if (scrollY <= curtainHeigh) {
                                scrollTo(0, curtainHeigh - scrollY);
                            }
                        }
                    }
                    break;
                case MotionEvent.ACTION_UP:
                    upY = (int) event.getRawY();
                    if (Math.abs(upY - downY) < 10) {
//                        onRopeClick();
                        break;
                    } else if (downY > upY) {
                        if (isOpen) {
                            //只要是有向上滑动动作就划上去
//                            if (Math.abs(scrollY) > curtainHeigh / 2) {
                            if (Math.abs(scrollY) > curtainHeigh / 20) {
                                startMoveAnim(this.getScrollY(),
                                        (curtainHeigh - this.getScrollY()), upDuration);
                                isOpen = false;
                                EventBus.getDefault().post(new CurtainIsShownEvent(isOpen));
                            } else {
                                startMoveAnim(this.getScrollY(), -this.getScrollY(), upDuration);
                                isOpen = true;
                                EventBus.getDefault().post(new CurtainIsShownEvent(isOpen));
                            }
                        }
                    } else {
                        if (scrollY > curtainHeigh / 2) {
                            startMoveAnim(this.getScrollY(), -this.getScrollY(), upDuration);
                            isOpen = true;
                            EventBus.getDefault().post(new CurtainIsShownEvent(isOpen));
                        } else {
                            startMoveAnim(this.getScrollY(), (curtainHeigh - this.getScrollY()), upDuration);
                            isOpen = false;
                            EventBus.getDefault().post(new CurtainIsShownEvent(isOpen));
                        }
                    }
                    break;
                default:
                    break;
            }
        }
        return false;
    }

    public void performContinueTracking() {
        mSpeedViewStatus = SPEED_STATUS.SPEED_STATUS_RUNNING;
        mSpeedMeter.performContinue();
    }

    public void performStopTracking() {
        mSpeedViewStatus = SPEED_STATUS.SPEED_STATUS_READY;
        switchStatus();
        mSpeedMeter.performStop();
    }

    public void onRopeClick() {
        if (isOpen) {
            NewCurtainView.this.startMoveAnim(0, curtainHeigh, upDuration);
            mSpeedMeter.showSpeedMeter(false); //used for click map when running
        } else {
            NewCurtainView.this.startMoveAnim(curtainHeigh, -curtainHeigh, downDuration);
            mSpeedMeter.showSpeedMeter(true);
        }
        isOpen = !isOpen;
        EventBus.getDefault().post(new CurtainIsShownEvent(isOpen));
    }

    public void setSpeedMeterTime(long time) {
        if (mSpeedMeter.getSpeedStatus() == SpeedMeterView.SPEED_STATUS.SPEED_STATUS_RUNNING) {
            mSpeedMeter.setTime(time);
        }
    }

    public void setSpeedMeterSpeed(int speed) {
        LogUtils.d(TAG, "set speed = " + speed);
        if (mSpeedMeter.getSpeedStatus() == SpeedMeterView.SPEED_STATUS.SPEED_STATUS_RUNNING) {
            mSpeedMeter.setValue(speed);
            addSpeedData(speed);
        }
    }

    public void setSpeedMeterRpm(int rpm) {
        if (mSpeedMeter.getSpeedStatus() == SpeedMeterView.SPEED_STATUS.SPEED_STATUS_RUNNING) {
            mSpeedMeter.setRpm(rpm);
        }
    }

    public void updatePersonaProfile(Double mileage, Long total, Long rank) {
        if (mileage != null) {
            mStatTotalDistance.setValue((int) mileage.doubleValue());
        }

        if (total != null) {
            mStatTotalTime.setTime(total.longValue());
        }
    }

    /********************************
     * speed chart
     ********************************/

    private void addSpeedData(int speed) {
        LogUtils.d(TAG, "add new speed = " + speed);
        PointValue pv = new PointValue(mPointIndex, speed);
        mSpeedPointValueList.add(pv);
        PointValue pvg = new PointValue(mPointIndex, calculateGValue(speed));
        mGPointValueList.add(pvg);
        if (isOpen) {
            updateViewport(speed);
        }
        mPointIndex++;
    }

    private float calculateGValue(int speed) {
        float preV = (mPointIndex > 0) ? mSpeedPointValueList.get(mPointIndex - 1).getY() : 0f;
        return ((float) speed - preV) / 1;
    }

    private void updateViewport(int speed) {
        Viewport vMax = new Viewport(mSpeedChart.getMaximumViewport());
        if (speed > mMaxSpeedInWindow) {
            mMaxSpeedIndex = mPointIndex;
            mMaxSpeedInWindow = speed;
        }

        if (mPointIndex > mSpeedChartWindowSize) {
            vMax.right = mPointIndex;
            mSpeedChart.setMaximumViewport(vMax);
            // update the top value for current view port
            Log.d(TAG, "updateViewport: refine left=" + vMax.left + ", right=" + vMax.right);
        }

        Viewport vCurrent = new Viewport(mSpeedChart.getCurrentViewport());
        vCurrent.left = vMax.right - mSpeedChartWindowSize;
        vCurrent.right = vMax.right;
        if (vCurrent.top < mMaxSpeedInWindow) {
            vCurrent.top = mMaxSpeedInWindow + 5;
        } else if (vMax.left > mMaxSpeedIndex) {
            // find another max
            findMax(mMaxSpeedIndex, mSpeedChartWindowSize);
            vCurrent.top = mMaxSpeedInWindow + 5;
        }
        mSpeedChart.setCurrentViewport(vCurrent);
    }

    private void findMax(int startIndex, int windowSize) {
        int max = 0;
        int index = -1;
        for (int i = startIndex; i < startIndex + windowSize; i++) {
            if (mSpeedPointValueList.get(i).getY() > max) {
                max = (int) mSpeedPointValueList.get(i).getY();
                index = i;
            }
        }
        mMaxSpeedIndex = index;
        mMaxSpeedInWindow = max;

    }

    private void resetChartData() {
        mSpeedPointValueList.clear();
        mGPointValueList.clear();
        mPointIndex = 0;
        mMaxSpeedIndex = 0;
        mMaxSpeedInWindow = 0;
    }

    private void resetViewport() {
        // Reset viewport height range to (0,200)
        final Viewport v = new Viewport(mSpeedChart.getMaximumViewport());
        v.bottom = 0;
        v.top = MAX_SPEED;
        v.left = 0;
        v.right = mSpeedChartWindowSize;
        mSpeedChart.setMaximumViewport(v);
        v.top = 10; // initial value should changed by speed change;
        mSpeedChart.setCurrentViewport(v);

    }

    private void initLines() {

        SpeedLine = new Line();
        SpeedLine.setColor(SPEED_COLOR);
        SpeedLine.setCubic(true);
        SpeedLine.setFilled(true);
        SpeedLine.setHasLabels(false);
        SpeedLine.setHasLabelsOnlyForSelected(false);
        SpeedLine.setHasLines(true);
        SpeedLine.setHasPoints(false);
        SpeedLine.setShape(ValueShape.CIRCLE);
        SpeedLine.setAreaTransparency(200); //%80*255
        SpeedLine.setStrokeWidth(SpeedLine.getStrokeWidth() / 2);

        GLine = new Line(SpeedLine);
        GLine.setColor(G_COLOR);

        List<Line> lines = new ArrayList<Line>();
        mSpeedPointValueList.add(new PointValue(0, 0));
        SpeedLine.setValues(mSpeedPointValueList);
        mGPointValueList.add(new PointValue(0, 0));
        GLine.setValues(mGPointValueList);
        lines.add(SpeedLine);
//        lines.add(GLine);

        mSpeedChartData = new LineChartData(lines);

        Axis axisX = new Axis();
        Axis axisY = new Axis().setHasLines(true);
        mSpeedChartData.setAxisXBottom(axisX);
        mSpeedChartData.setAxisYRight(axisY);

        mSpeedChartData.setBaseValue(Float.NEGATIVE_INFINITY);
        mSpeedChart.setLineChartData(mSpeedChartData);
    }

    public void initMap(Bundle savedInstanceState) {
        mSmallMapView.onCreate(savedInstanceState);
        initMap();
    }

    public void onResume() {
        if (mSmallMapView != null) {
            mSmallMapView.onResume();
            initMap();
        }
    }

    public void onPause() {
        if (mSmallMapView != null) {
            mSmallMapView.onPause();
        }
    }


    public void onSaveInstanceState(Bundle outState) {
        if (mSmallMapView != null) {
            mSmallMapView.onSaveInstanceState(outState);
        }
    }

    public void onDestroy() {
        if (mSmallMapView != null) {
            mSmallMapView.onDestroy();
        }
    }

    private void initMap() {

        if (aMap == null) {
            aMap = mSmallMapView.getMap();
            setMapUi();
        }
        setTraffic();


        AMapLocation location = GlobalContext.getLocationClient().getLastKnownLocation();
        moveCamera(location);

    }

    private void setMapUi() {
        UiSettings mUiSettings = aMap.getUiSettings();
        mUiSettings.setZoomControlsEnabled(false);
        mUiSettings.setLogoPosition(AMapOptions.LOGO_POSITION_BOTTOM_LEFT);

//        aMap.setLocationSource(this);// 设置定位监听
//        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
//        // 设置定位的类型为定位模式：定位（AMap.LOCATION_TYPE_LOCATE）、跟随（AMap.LOCATION_TYPE_MAP_FOLLOW）
//        // 地图根据面向方向旋转（AMap.LOCATION_TYPE_MAP_ROTATE）三种模式
//        aMap.setMyLocationType(AMap.LOCATION_TYPE_MAP_FOLLOW);

    }

    private void setTraffic() {
        MyTrafficStyle myTrafficStyle = new MyTrafficStyle();
        myTrafficStyle.setSeriousCongestedColor(0xff92000a);
        myTrafficStyle.setCongestedColor(0xffea0312);
        myTrafficStyle.setSlowColor(0xffff7508);
        myTrafficStyle.setSmoothColor(0xff00a209);
        aMap.setTrafficEnabled(false);
    }


    public void setLocation(AMapLocation location) {
        if (isMove || !isOpen) {
            return;
        }
        LogUtils.d(TAG, "setLocation  lat:" + location.getLatitude() + ",lon:" + location.getLongitude());
        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
        drawMyMarker(latLng);
        moveCamera(location);
//        mListener.onLocationChanged(location);


    }
//
//    @Override
//    public void activate(OnLocationChangedListener onLocationChangedListener) {
//        mListener = onLocationChangedListener;
//    }
//
//    @Override
//    public void deactivate() {
//        mListener = null;
//    }

    /*
     * draw own marker
     */
    protected void drawMyMarker(LatLng latLng) {
        if (myMarker != null && !myMarker.isVisible()) {
            myMarker.destroy();
            myMarker = null;
        }

        if (myMarker == null) {
            Bitmap locationMe = BitmapUtils.zoomBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.location_me), 100, 100);
            BitmapDescriptor icon = BitmapDescriptorFactory.fromBitmap(locationMe);
            myMarker = aMap.addMarker(new MarkerOptions().draggable(false).icon(icon).position(latLng));
        } else {
            myMarker.setPosition(latLng);
        }

    }

    protected void moveCamera(AMapLocation location) {
        LatLng latLng;
        CameraPosition cameraPosition;
        if (location != null) {
            latLng = new LatLng(location.getLatitude(), location.getLongitude());
            drawMyMarker(latLng);
            cameraPosition = new CameraPosition.Builder()
                    .target(latLng).zoom(Constants.DEFAULT_ZOOM_LEVEL).bearing(0).tilt(30).build();

        } else {
            cameraPosition = new CameraPosition.Builder()
                    .target(Constants.DEFAULT_LATLNG).zoom(Constants.DEFAULT_ZOOM_LEVEL).bearing(0).tilt(30).build();
        }


        CameraUpdate update = CameraUpdateFactory.newCameraPosition(cameraPosition);
        aMap.moveCamera(update);
    }

    public void updateRank(long rank) {
        int totalCircle = FriendHelper.getInstance().getContactList().size() + 1;
        int percentage = (int)((double)rank / totalCircle * 100);
        mStatTop.setProgress(percentage);
        if (rank == 1){
            mStatTop.setIconResource(getResources().getDrawable(R.drawable.gold_medal));
        } else if (rank == 2){
            mStatTop.setIconResource(getResources().getDrawable(R.drawable.silver_medal));
        } else if (rank == 3){
            mStatTop.setIconResource(getResources().getDrawable(R.drawable.bronze_medal));
        } else {
            mStatTop.setCommonValue(rank + "");
        }

    }

    public void updateMileAndTime(double meters, long total) {
        if (meters > 0) {
            //将米转换成公里。
            double mileages = (meters / 1000f);
            //如果小于等于10公里则公里数保留一位小数否则公里数取整数。
            if (mileages <= 10) {
                double avgSpeed = (mileages / (total / (1000f * 3600f)));
                //如果平均速度小于0.1平均速度为0.
                if (avgSpeed >= 0) {
                    if (avgSpeed < 0.1) {
                        mStatAverSpeed.setValue(0);
                    } else {
                        mStatAverSpeed.setValue(FormatUtils.doubleDistance1(avgSpeed));
                    }
                }
                mStatTotalDistance.setValue(FormatUtils.doubleDistance1(mileages));
            } else {
                double avgSpeed = (mileages / (total / (1000f * 3600)));

                if (avgSpeed >= 0) {
                    mStatAverSpeed.setValue(FormatUtils.doubleDistance1(avgSpeed));
                }
                mStatTotalDistance.setValue(FormatUtils.doubleDistance1(mileages));
            }

        }

        if (total > 0) {
            mStatTotalTime.setTime(total);
        }
    }

}
